const express = require('express');
const bcrypt = require('bcryptjs');
const User = require('../models/user');
const { pool } = require('../config/db');
const { authMiddleware, adminMiddleware } = require('../middleware/auth');

const router = express.Router();

// @route   GET api/users/profile
// @desc    Get user profile
// @access  Private
router.get('/profile', authMiddleware, async (req, res) => {
  try {
    const user = await User.findById(req.user.id);
    
    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }
    
    res.json(user);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   PUT api/users/profile
// @desc    Update user profile
// @access  Private
router.put('/profile', authMiddleware, async (req, res) => {
  try {
    const { full_name, phone, address } = req.body;
    
    // Create user data object
    const userData = {
      full_name,
      phone,
      address
    };
    
    const updatedUser = await User.update(req.user.id, userData);
    res.json(updatedUser);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   PUT api/users/password
// @desc    Change password
// @access  Private
router.put('/password', authMiddleware, async (req, res) => {
  try {
    const { current_password, new_password } = req.body;
    
    // Get user with password
    const [rows] = await pool.query('SELECT * FROM users WHERE id = ?', [req.user.id]);
    const user = rows[0];
    
    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }
    
    // Check if current password is correct
    const isMatch = await bcrypt.compare(current_password, user.password);
    if (!isMatch) {
      return res.status(400).json({ message: 'Current password is incorrect' });
    }
    
    // Change password
    await User.changePassword(req.user.id, new_password);
    
    res.json({ message: 'Password updated successfully' });
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   GET api/users/count
// @desc    获取用户总数
// @access  公开
router.get('/count', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT COUNT(*) as count FROM users');
    console.log('获取用户总数:', rows[0].count);
    res.json({ count: rows[0].count });
  } catch (err) {
    console.error('获取用户总数失败:', err);
    res.status(500).json({ message: '服务器错误' });
  }
});

// @route   GET api/users
// @desc    Get all users (admin only)
// @access  Private/Admin
router.get('/', [authMiddleware, adminMiddleware], async (req, res) => {
  try {
    // Simple implementation - in a real app, you'd want pagination
    const [rows] = await pool.query(
      'SELECT id, username, email, full_name, phone, address, is_admin, created_at FROM users'
    );
    
    res.json(rows);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   GET api/users/:id
// @desc    Get user by ID
// @access  Private
router.get('/:id', authMiddleware, async (req, res) => {
  try {
    const userId = req.params.id;
    
    // 验证用户权限
    if (!req.user.is_admin && req.user.id !== parseInt(userId)) {
      return res.status(403).json({ message: '没有权限访问其他用户的信息' });
    }
    
    console.log('获取用户信息 - 用户ID:', userId);
    console.log('当前用户:', req.user);
    
    const user = await User.findById(userId);
    
    if (!user) {
      return res.status(404).json({ message: '未找到该用户' });
    }
    
    // 不返回密码等敏感信息
    delete user.password;
    res.json(user);
  } catch (err) {
    console.error('获取用户信息失败:', err);
    res.status(500).json({ message: '服务器错误' });
  }
});

// @route   PUT api/users/:id
// @desc    Update user by ID (admin only)
// @access  Private/Admin
router.put('/:id', [authMiddleware, adminMiddleware], async (req, res) => {
  try {
    const userId = req.params.id;
    const { email, full_name, phone, address } = req.body;
    
    // Check if user exists
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }
    
    // Update user using the model method
    const userData = { email, full_name, phone, address };
    const updatedUser = await User.adminUpdate(userId, userData);
    
    res.json(updatedUser);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   PUT api/users/:id/admin
// @desc    Toggle admin status for a user (admin only)
// @access  Private/Admin
router.put('/:id/admin', [authMiddleware, adminMiddleware], async (req, res) => {
  try {
    const userId = req.params.id;
    const { is_admin } = req.body;
    
    // Validate request
    if (typeof is_admin !== 'boolean') {
      return res.status(400).json({ message: 'Invalid admin status' });
    }
    
    // Prevent self-demotion
    if (parseInt(userId) === req.user.id && !is_admin) {
      return res.status(400).json({ message: 'Cannot remove your own admin privileges' });
    }
    
    // Check if user exists
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }
    
    // Update admin status using the model method
    const updatedUser = await User.updateAdminStatus(userId, is_admin);
    
    res.json({ 
      message: 'Admin status updated successfully',
      user: updatedUser
    });
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

module.exports = router; 